<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Inbox extends ORM {
    
    /*
     * Inbox belongs to message and user, 
     * 
     */

    protected $_belongs_to = array(
                'message' => array('model' => 'message', 'foreign_key' => 'message_id'),
                'user'    => array('model' => 'user', 'foreign_key' => 'user_id')
    );
    
    public function get_inbox($user_id, $limit = null, $page = null, $word = null)
    {
        $temp_inboxes = $this->select('messages.subject',
                                      'messages.content_message',
                                      'messages.date_created',
                                      'user_profiles.name', 
                                      'user_profiles.surname', 
                                      'user_profiles.description', 
                                      'user_profiles.url',
                                      array('user_profiles.file_id','photo'),
                                      array('files.id','file_id'),
                                      array('files.name','file_name'),
                                      array('files.extension','file_extension'))
                             ->join('messages')->on('messages.id','=','inboxes.message_id')
                             ->join('outboxes')->on('outboxes.message_id', '=', 'messages.id')
                             ->join('user_profiles')->on('outboxes.user_id', '=', 'user_profiles.user_id')
                             ->join('files','LEFT')->on('user_profiles.file_id', '=', 'files.id')
                             ->where('inboxes.deleted','=',0)
                             ->where('inboxes.folder','=',0)
                             ->where('inboxes.user_id', '=', $user_id)
                             ->order_by('inboxes.id','DESC');
        
        if ($limit)
        {
            $temp_inboxes->limit($limit);
            if ($page)
            {
                $offset = $limit * ($page - 1);
                $temp_inboxes->offset($offset);
            }
        }
        
        if ($word)
        {
            $temp_inboxes->where_open()
                        ->where('messages.subject', 'LIKE', '%'.$word.'%')
                        ->or_where('messages.content_message', 'LIKE', '%'.$word.'%')
                     ->where_close();
        }
        
        $temp_inboxes = $temp_inboxes->find_all();
        
        $inboxes = array();
        foreach($temp_inboxes as $inbox)
        { 
            $inbox->photo = Media::get_file_path($inbox->file_name, 
                                            $inbox->file_id, 
                                            $inbox->file_extension, 
                                            true, 
                                            'mini_square', 
                                            false);
            $inboxes[] = $inbox;
        }
        return $inboxes;
        
       
    }
}